# app/services/mqtt_service.py
from flask_mqtt import Mqtt
import json


class MQTTService:
    def __init__(self, broker, port):
        self.client = mqtt.Client()
        # if username and password:
        #     self.client.username_pw_set(username, password)
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message  # 添加消息接收回调
        self.client.connect(broker, port, 60)
        self.client.loop_start()

    def on_connect(self, client, userdata, flags, rc):
        print("Connected with result code " + str(rc))
        # 可以在这里订阅需要的主题
        client.subscribe("/flask/test")

    def on_message(self, client, userdata, message):
        print("Received message '" + str(message.payload) + "' on topic '" + message.topic + "'")

    def publish_message(self, topic, payload):
        self.client.publish(topic, json.dumps(payload))
